package com.bluegalaxy.nhb.snapi.controller.api.ck;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bluegalaxy.nhb.service.AnalyseSqlService;
import com.bluegalaxy.nhb.snapi.core.common.UntisCom;
import com.bluegalaxy.nhb.snservice.common.utils.DateUtil;
import com.bluegalaxy.nhb.snservice.common.utils.StringUtil;
import com.bluegalaxy.nhb.snservice.domain.constant.AppConstant;
import com.bluegalaxy.nhb.snservice.domain.vo.api.R;
import com.bluegalaxy.nhb.snservice.domain.vo.api.ck.OverviewReq;
import com.bluegalaxy.nhb.snservice.domain.vo.api.ck.OvervivwResVO;
import com.bluegalaxy.nhb.snservice.domain.vo.api.ck.OvervivwVO;
import com.bluegalaxy.nhb.snservice.service.ck.OverviewService;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.bluegalaxy.nhb.snservice.domain.constant.CkConstant.*;
import static java.util.Comparator.comparing;

/**
 * 基础指标
 */
@RestController
@RequestMapping(AppConstant.APPLICATION_NAME+"/basicindicators")
@Api(value = "基础指标监控", tags = "基础指标监控API")
public class BasicIndicatorsController {
    private static Log log = LogFactory.getLog(BasicIndicatorsController.class);

    @Autowired
    private OverviewService overviewService;
    @Resource
    private AnalyseSqlService sqlService;

    //同比
    private  final  static  int YEAR_ON_YEAR=-1;
    //环比
    private  final  static  int CHAIN_COMPARISON=-7;
    //同比
    private  final  static  String ONYEARFLOW="01";
    private  final  static  String A="A";
    //环比
    private  final  static  String COMPARISON="02";
    private  final  static  String B="B";
    //全站流量
    private  final  static  String TOTALNUM="TOTALNUM";
    //全站日活
    private  final  static  String DAYNUM="DAYNUM";
    //注册用户数
    private  final  static  String LOGINUSERNUM="LOGINUSERNUM";
    //下单人数
    private  final  static  String SUBMITORDERNUM="SUBMITORDERNUM";
    //GMV
    private  final  static  String AMOUNTPAIDLIST="AMOUNTPAIDLIST";
    //订单量
    private  final  static  String ORDERVOLUMENUM="ORDERVOLUMENUM";
    //下单转换
    private  final  static  String PAYORDERNUM="PAYORDERNUM";
    //客单价
    private  final  static  String AVGPRICENUM="AVGPRICENUM";
    //app使用时长
    private  final  static  String AVGEVENTTIMENUM="AVGEVENTTIMENUM";
    //过去7天日活
    private  final  static  String DAILYLIFELIST="DAILYLIFELIST";
    //过去7天新用户访问数
    private  final  static  String NEWUSERLIST="NEWUSERLIST";
    //各端过去7天日活
    private  final  static  String PLATFORMLIST="PLATFORMLIST";
    //过去7天新访问用户占比
    private  final  static  String USERTAGEMLIST="USERTAGEMLIST";
    //Web端平均访问时长
    private  final  static  String WEBAVGDURATIONLIST="WEBAVGDURATIONLIST";
    //全站流量用户数
    private  final  static  String WTOTALNUMLIST="WTOTALNUMLIST";


    @ResponseBody
    @PostMapping("/findOverview")
    @ApiOperation(value = "查询基础指标", notes = "查询基础指标")
    public R findOverview(@RequestBody JSONObject  paramVO) {
        String startDate=paramVO.getString("startDate");
        String endDate=paramVO.getString("endDate");
        String combine=paramVO.getString("combine");
        String eventName=paramVO.getString("eventName");
        String methodName=paramVO.getString("methodName");
        String fieldName=paramVO.getString("fieldName");
        String startContrastDate=paramVO.getString("startContrastDate");
        String endContrastDate=paramVO.getString("endContrastDate");
        Integer beforeDay=paramVO.getInteger("beforeDay");
        JSONArray jsonArray = paramVO.getJSONArray("ruleExpression");
        JSONArray applicationCodeArray = paramVO.getJSONArray("applicationCodeArray");
        JSONObject jsonParam = paramVO.getJSONObject("jsonParam");
        //任务类型
        String taskType= paramVO.getString("taskType");
        String sSql=UntisCom.beforeWhere(methodName,fieldName);
//        String wSql= UntisCom.aflerWhere(jsonArray,applicationCodeArray);
        //queryItems 参数解决
        String itemSql = sqlService.analyseSql(jsonParam,m_overview,queryItems);
        //userAttributes 参数解析
        String userSql = sqlService.analyseSql(jsonParam,m_overview,userAttributes);
        String wSql = itemSql+userSql;
        OverviewReq overviewReq=new OverviewReq();
        overviewReq.setStartDate(startDate);
        overviewReq.setEndDate(endDate);
        overviewReq.setsSql(sSql);
        overviewReq.setwSql(wSql);
        overviewReq.setEventName("");
        overviewReq.setGroupBy("");
        overviewReq.setBeforeDay(beforeDay);
        if (applicationCodeArray != null && !applicationCodeArray.isEmpty()){
            overviewReq.setApplicationCodeList(applicationCodeArray.toJavaList(String.class));
        }

        //全站流量开始
        Map<String, Object> paramMap =new HashMap<>();

        //全站流量
        if(TOTALNUM.equals(taskType)){
            //当天
            paramMap.put("totalNum",overviewService.overvivwVOListCount(overviewReq));
            //同比
            getOverviewReq(overviewReq,startDate,endDate,YEAR_ON_YEAR);
            paramMap.put("totalNum"+A, overviewService.overvivwVOListCount(overviewReq));
            //环比
            getOverviewReq(overviewReq,startDate,endDate,CHAIN_COMPARISON);
            paramMap.put("totalNum"+B,overviewService.overvivwVOListCount(overviewReq));
        }
        //全站日活
        else if(DAYNUM.equals(taskType)){
            sSql=" COUNT(DISTINCT e.distinct_id)  eventCount";
            overviewReq.setsSql(sSql);
            overviewReq.setStartDate(startDate);
            overviewReq.setEndDate(endDate);
            paramMap.put("dayNum",overviewService.overvivwVOListCount(overviewReq));
            //同比
            getOverviewReq(overviewReq,startDate,endDate,YEAR_ON_YEAR);
            paramMap.put("dayNum"+A, overviewService.overvivwVOListCount(overviewReq));
            //环比
            getOverviewReq(overviewReq,startDate,endDate,CHAIN_COMPARISON);
            paramMap.put("dayNum"+B,overviewService.overvivwVOListCount(overviewReq));
        }
        //注册用户数
        else if(LOGINUSERNUM.equals(taskType)){
            sSql="  COUNT(DISTINCT e.login_id)  eventCount";
            overviewReq.setsSql(sSql);
            overviewReq.setStartDate(startDate);
            overviewReq.setEndDate(endDate);
            //当天
            paramMap.put("loginUserNum",overviewService.overvivwVOListCount(overviewReq));
            //同比
            getOverviewReq(overviewReq,startDate,endDate,YEAR_ON_YEAR);
            paramMap.put("loginUserNum"+A, overviewService.overvivwVOListCount(overviewReq));
            //环比
            getOverviewReq(overviewReq,startDate,endDate,CHAIN_COMPARISON);
            paramMap.put("loginUserNum"+B,overviewService.overvivwVOListCount(overviewReq));
        }
        //下单人数
        else if(SUBMITORDERNUM.equals(taskType)){
            getSubmitOrderNum(paramMap,overviewReq,startDate,endDate);
        }
        //GMV 查询过去7天
        else if(AMOUNTPAIDLIST.equals(taskType)){
            //订单实际支付金额总和
            sSql=UntisCom.getSsqlAmount("SUM","order_actual_amount");
            overviewReq.setsSql(sSql);
            if (startDate.equals(endDate)){
                startDate = DateUtil.getOneDayYYYYMMDD(endDate,overviewReq.getBeforeDay() == null?CHAIN_COMPARISON:overviewReq.getBeforeDay());
            }
            overviewReq.setStartDate(startDate);
            overviewReq.setEndDate(endDate);
            overviewReq.setEventName("PayOrder");

            OvervivwResVO overviewRes = getOvervivwRes(overviewReq);

            paramMap.put("amountPaid",overviewRes);
        }
        //订单量
        else if(ORDERVOLUMENUM.equals(taskType)){
            getOrderVolumeNum(paramMap,overviewReq,startDate,endDate);
        }
        //下单转换
        else if(PAYORDERNUM.equals(taskType)){
            //获取订单量
            getOrderVolumeNum(paramMap,overviewReq,startDate,endDate);
            //下单支付的订单数/订单总数
            sSql="  COUNT(DISTINCT e.distinct_id)  eventCount  ";
            overviewReq.setsSql(sSql);
            overviewReq.setStartDate(startDate);
            overviewReq.setEndDate(endDate);
            overviewReq.setEventName("PayOrder");
//            System.out.println(overviewService.overvivwVOListCount(overviewReq));
//            System.out.println(paramMap.get("orderVolumeNum"));
            //当天
            paramMap.put("payOrderNum",StringUtil.numberFormat(0,overviewService.overvivwVOListCount(overviewReq),String.valueOf(paramMap.get("orderVolumeNum"))));
            //同比
            getOverviewReq(overviewReq,startDate,endDate,YEAR_ON_YEAR);
            paramMap.put("payOrderNum"+A, StringUtil.numberFormat(0,overviewService.overvivwVOListCount(overviewReq),String.valueOf(paramMap.get("orderVolumeNumA"))));
            //环比
            getOverviewReq(overviewReq,startDate,endDate,CHAIN_COMPARISON);
            paramMap.put("payOrderNum"+B,StringUtil.numberFormat(0,overviewService.overvivwVOListCount(overviewReq),String.valueOf(paramMap.get("orderVolumeNumB"))));
        }
        //客单价
        else if(AVGPRICENUM.equals(taskType)){
            //先查询总订单金额/下单人数
            getSubmitOrderNum(paramMap,overviewReq,startDate,endDate);
            sSql=UntisCom.getSsql("SUM","order_amount");
            overviewReq.setsSql(sSql);
            overviewReq.setStartDate(startDate);
            overviewReq.setEndDate(endDate);
            overviewReq.setEventName("SubmitOrder");
            paramMap.put("avgPriceNum",StringUtil.numberFormat(1,overviewService.overvivwVOListCount(overviewReq),String.valueOf(paramMap.get("submitOrderNum"))));
            //同比
            getOverviewReq(overviewReq,startDate,endDate,YEAR_ON_YEAR);
            paramMap.put("avgPriceNum"+A, StringUtil.numberFormat(1,overviewService.overvivwVOListCount(overviewReq),String.valueOf(paramMap.get("submitOrderNumA"))));
            //环比
            getOverviewReq(overviewReq,startDate,endDate,CHAIN_COMPARISON);
            paramMap.put("avgPriceNum"+B,StringUtil.numberFormat(1,overviewService.overvivwVOListCount(overviewReq),String.valueOf(paramMap.get("submitOrderNumB"))));
        }
        //app使用时长
        else if(AVGEVENTTIMENUM.equals(taskType)){
            sSql=UntisCom.getSsql("AVG","event_duration");
            overviewReq.setsSql(sSql);
            overviewReq.setStartDate(startDate);
            overviewReq.setEndDate(endDate);
            overviewReq.setEventName("");
            paramMap.put("avgEventTimeNum",StringUtil.coinToYuan(overviewService.overvivwVOListCount(overviewReq)));
            //同比
            getOverviewReq(overviewReq,startDate,endDate,YEAR_ON_YEAR);
            paramMap.put("avgEventTimeNum"+A, StringUtil.coinToYuan(overviewService.overvivwVOListCount(overviewReq)));
            //环比
            getOverviewReq(overviewReq,startDate,endDate,CHAIN_COMPARISON);
            paramMap.put("avgEventTimeNum"+B,StringUtil.coinToYuan(overviewService.overvivwVOListCount(overviewReq)));
        }
        //过去7天日活
        else if(DAILYLIFELIST.equals(taskType)){
            getDailyLifeList(paramMap,overviewReq,startDate,endDate);
        }
        //过去7天新用户访问数
        else if(NEWUSERLIST.equals(taskType)){
            getNewUserList(paramMap,overviewReq,startDate,endDate);
        }
        //各端过去7天日活 todo 待优化
        else if(PLATFORMLIST.equals(taskType)){
            sSql=" COUNT(DISTINCT e.anonymous_id)  eventAmount,e.lib1  platformType ";
            overviewReq.setsSql(sSql);
            if (startDate.equals(endDate)){
                startDate = DateUtil.getOneDayYYYYMMDD(endDate,overviewReq.getBeforeDay() == null?CHAIN_COMPARISON:overviewReq.getBeforeDay());
            }
            overviewReq.setStartDate(startDate);
            overviewReq.setEndDate(endDate);
            overviewReq.setEventName("");
            overviewReq.setGroupBy(" ,e.lib1  ");
            overviewReq.setCombine("");
            overviewReq.setwSql(wSql);

            overviewReq.setTaskType(taskType);
            OvervivwResVO overviewRes = getOvervivwRes(overviewReq);
//            List<OvervivwVO> platformList=overvivwVOList(overviewReq);
            paramMap.put("platform",overviewRes);
        }
        //过去7天新访问用户占比
        else if(USERTAGEMLIST.equals(taskType)){
            //过去7天新用户访问数开始/过去7天日活
            getDailyLifeList(paramMap,overviewReq,startDate,endDate);
            getNewUserList(paramMap,overviewReq,startDate,endDate);
//            List<OvervivwVO> userTagemList=getUserTagemList((List<OvervivwVO>)paramMap.get("dailyLifeList"),(List<OvervivwVO>)paramMap.get("newUserList"));
//            paramMap.put("userTagemList",userTagemList);
            OvervivwResVO resVO = getUserTagem((OvervivwResVO)paramMap.get("dailyLife"),(OvervivwResVO)paramMap.get("newUser"));
            paramMap.put("userTagem",resVO);
        }
        //Web端平均访问时长
        else if(WEBAVGDURATIONLIST.equals(taskType)){
            sSql=UntisCom.getSsqlAmount("AVG","event_duration");
            overviewReq.setsSql(sSql);
            if (startDate.equals(endDate)){
                startDate = DateUtil.getOneDayYYYYMMDD(endDate,overviewReq.getBeforeDay() == null?CHAIN_COMPARISON:overviewReq.getBeforeDay());
            }
            overviewReq.setStartDate(startDate);
            overviewReq.setEndDate(endDate);
            overviewReq.setEventName("WebStay");
            overviewReq.setGroupBy("");
            overviewReq.setCombine("");
            overviewReq.setwSql(wSql+" and e.lib1='js'");

            OvervivwResVO overviewRes = getOvervivwRes(overviewReq);

//
//            List<OvervivwVO> webAvgDurationList=overvivwVOList(overviewReq);
//            initWebAvgDurationList(webAvgDurationList);
            paramMap.put("webAvgDuration",overviewRes);
        }
        //全站流量用户数
        else if(WTOTALNUMLIST.equals(taskType)){
            sSql=" COUNT(1)  eventAmount ";
            overviewReq.setsSql(sSql);
            if (startDate.equals(endDate)){
                startDate = DateUtil.getOneDayYYYYMMDD(endDate,overviewReq.getBeforeDay() == null?CHAIN_COMPARISON:overviewReq.getBeforeDay());
            }
            overviewReq.setStartDate(startDate);
            overviewReq.setEndDate(endDate);
            overviewReq.setEventName("");
            overviewReq.setCombine("");
            overviewReq.setwSql(wSql);

            OvervivwResVO overviewRes = getOvervivwRes(overviewReq);
//            List<OvervivwVO> wtotalNumList=overvivwVOList(overviewReq);
            paramMap.put("wtotalNum",overviewRes);
        }
        return R.data(paramMap);
    }

    //下单人数
    public  void  getSubmitOrderNum(Map<String, Object> paramMap ,OverviewReq overviewReq,String startDate,String endDate ){
        String sSql="  COUNT(DISTINCT e.distinct_id)  eventCount";
        overviewReq.setsSql(sSql);
        overviewReq.setStartDate(startDate);
        overviewReq.setEndDate(endDate);
        overviewReq.setEventName("SubmitOrder");
        //当天
        String submitOrderNum=overviewService.overvivwVOListCount(overviewReq);
        paramMap.put("submitOrderNum",submitOrderNum);
        //同比
        getOverviewReq(overviewReq,startDate,endDate,YEAR_ON_YEAR);
        String submitOrderNumA=overviewService.overvivwVOListCount(overviewReq);
        paramMap.put("submitOrderNum"+A, submitOrderNumA);
        //环比
        getOverviewReq(overviewReq,startDate,endDate,CHAIN_COMPARISON);
        String submitOrderNumB=overviewService.overvivwVOListCount(overviewReq);
        paramMap.put("submitOrderNum"+B,submitOrderNumB);
    }

    //订单量
    public  void  getOrderVolumeNum(Map<String, Object> paramMap ,OverviewReq overviewReq,String startDate,String endDate ){
        String  sSql="  COUNT(1)  eventCount ";
        overviewReq.setsSql(sSql);
        overviewReq.setStartDate(startDate);
        overviewReq.setEndDate(endDate);
        overviewReq.setEventName("SubmitOrderDetail");
        //当天
        String orderVolumeNum=overviewService.overvivwVOListCount(overviewReq);
        paramMap.put("orderVolumeNum",orderVolumeNum);
        //同比
        getOverviewReq(overviewReq,startDate,endDate,YEAR_ON_YEAR);
        String orderVolumeNumA=overviewService.overvivwVOListCount(overviewReq);
        paramMap.put("orderVolumeNum"+A, orderVolumeNumA);
        //环比
        getOverviewReq(overviewReq,startDate,endDate,CHAIN_COMPARISON);
        String orderVolumeNumB=overviewService.overvivwVOListCount(overviewReq);
        paramMap.put("orderVolumeNum"+B,orderVolumeNumB);
    }

    //实际支付订单量
    public  void  getPayOrderNum(Map<String, Object> paramMap ,OverviewReq overviewReq,String startDate,String endDate ){
        String  sSql="  COUNT(1)  eventCount ";
        overviewReq.setsSql(sSql);
        overviewReq.setStartDate(startDate);
        overviewReq.setEndDate(endDate);
        overviewReq.setEventName("PayOrder");
        //当天
        String orderVolumeNum=overviewService.overvivwVOListCount(overviewReq);
        paramMap.put("payOrderNum",orderVolumeNum);
        //环比
        getOverviewReq(overviewReq,startDate,endDate,YEAR_ON_YEAR);
        String orderVolumeNumA=overviewService.overvivwVOListCount(overviewReq);
        paramMap.put("payOrderNum"+A, orderVolumeNumA);
        //同比
        getOverviewReq(overviewReq,startDate,endDate,CHAIN_COMPARISON);
        String orderVolumeNumB=overviewService.overvivwVOListCount(overviewReq);
        paramMap.put("payOrderNum"+B,orderVolumeNumB);
    }

    //过去7天日活
    public  void  getDailyLifeList(Map<String, Object> paramMap ,OverviewReq overviewReq,String startDate,String endDate ){
        String sSql=" COUNT(DISTINCT e.anonymous_id)   eventAmount ";
        overviewReq.setsSql(sSql);
        if (startDate.equals(endDate)){
            startDate = DateUtil.getOneDayYYYYMMDD(endDate,overviewReq.getBeforeDay() == null?CHAIN_COMPARISON:overviewReq.getBeforeDay());
        }
        overviewReq.setStartDate(startDate);
        overviewReq.setEndDate(endDate);
        overviewReq.setEventName("");

        OvervivwResVO overviewRes = getOvervivwRes(overviewReq);

        paramMap.put("dailyLife",overviewRes);

    }

    //过去7天新用户访问
    public  void  getNewUserList(Map<String, Object> paramMap ,OverviewReq overviewReq,String startDate,String endDate ){

        String sSql=" COUNT(DISTINCT e.anonymous_id)   eventAmount ";
        overviewReq.setsSql(sSql);
        if (startDate.equals(endDate)){
            startDate = DateUtil.getOneDayYYYYMMDD(endDate,overviewReq.getBeforeDay() == null?CHAIN_COMPARISON:overviewReq.getBeforeDay());
        }
        overviewReq.setStartDate(startDate);
        overviewReq.setEndDate(endDate);
        overviewReq.setEventName("");
        //首次访问的用户
        overviewReq.setwSql(overviewReq.getwSql()+" and e.is_first_time='true'");

        OvervivwResVO overviewRes = getOvervivwRes(overviewReq);

        paramMap.put("newUser",overviewRes);

    }


    //Web端平均访问时长格式化处理
    private  void initWebAvgDurationList(List<OvervivwVO> webAvgDurationList){
        for (OvervivwVO overvivwVO:webAvgDurationList){
            overvivwVO.setEventCount(StringUtil.coinToYuan(overvivwVO.getEventCount()));
            overvivwVO.setEventAmount(new BigDecimal(StringUtil.coinToYuan(overvivwVO.getEventCount())));
            overvivwVO.setOnyearFlow(StringUtil.coinToYuan(overvivwVO.getOnyearFlow()));
            overvivwVO.setComparison(StringUtil.coinToYuan(overvivwVO.getComparison()));
        }
    }

    private OvervivwResVO getUserTagem(OvervivwResVO dailyLife,OvervivwResVO newUser){
        OvervivwResVO resVO = new OvervivwResVO();
        if(BigDecimal.ZERO.compareTo(dailyLife.getEventAmount()) == 0
                ||BigDecimal.ZERO.compareTo(newUser.getEventAmount()) == 0){
            resVO.setEventCount("0");
            resVO.setEventAmount(BigDecimal.ZERO);
        }else{
            resVO.setEventCount(StringUtil.coinToYuan(StringUtil.numberFormat(0,String.valueOf(dailyLife.getEventCount()),String.valueOf(newUser.getEventCount()))));
            resVO.setEventAmount(new BigDecimal(resVO.getEventCount()));
        }

        resVO.setTotalNum(BigDecimal.ZERO);
        if (dailyLife.getTotalNum().compareTo(BigDecimal.ZERO) > 0 && newUser.getTotalNum().compareTo(BigDecimal.ZERO) > 0 ){
            resVO.setTotalNum(newUser.getTotalNum().divide(dailyLife.getTotalNum(), 2, BigDecimal.ROUND_HALF_UP));
        }

        resVO.setAvgNum(BigDecimal.ZERO);
        if (dailyLife.getAvgNum().compareTo(BigDecimal.ZERO) > 0 && newUser.getAvgNum().compareTo(BigDecimal.ZERO) > 0 ){
            resVO.setAvgNum(newUser.getAvgNum().divide(dailyLife.getAvgNum(), 2, BigDecimal.ROUND_HALF_UP));
        }

        resVO.setComparison("0");
        if (!dailyLife.getComparison().equals("0") && !"0".equals(newUser.getAvgNum())){
            resVO.setComparison(new BigDecimal(newUser.getComparison()).divide(new BigDecimal(dailyLife.getComparison()), 2, BigDecimal.ROUND_HALF_UP).toString());
        }

        resVO.setOnyearFlow("0");
        if (!dailyLife.getOnyearFlow().equals("0") && !"0".equals(newUser.getOnyearFlow())){
            resVO.setOnyearFlow(new BigDecimal(newUser.getOnyearFlow()).divide(new BigDecimal(dailyLife.getOnyearFlow()), 2, BigDecimal.ROUND_HALF_UP).toString());
        }


        List<OvervivwVO> overvivwVOList = getUserTagemList(dailyLife.getOvervivwList(),newUser.getOvervivwList());
        resVO.setOvervivwList(overvivwVOList);
        return resVO;

    }

    //过去7天新用户访问数开始/过去7天日活=过去7天新访问用户占比
    private  List<OvervivwVO> getUserTagemList(List<OvervivwVO> dailyLifeList,List<OvervivwVO> newUserList){
        List<OvervivwVO> overvivwVOList=new ArrayList<>();
        for (OvervivwVO overvivwVO:dailyLifeList){
            OvervivwVO vos=new OvervivwVO();
            OvervivwVO vo=getOvervivwVO(overvivwVO.getEventDate(),newUserList);
            //计算同比环比
            vos.setEventDate(overvivwVO.getEventDate());
            if(overvivwVO.getEventAmount() == null || BigDecimal.ZERO.compareTo(overvivwVO.getEventAmount()) == 0
                    ||vo.getEventAmount() == null || BigDecimal.ZERO.compareTo(vo.getEventAmount()) == 0){
                vos.setEventCount("0");
                vos.setEventAmount(BigDecimal.ZERO);
            }else{
                vos.setEventCount(StringUtil.coinToYuan(StringUtil.numberFormat(0,String.valueOf(overvivwVO.getEventAmount()),String.valueOf(vo.getEventAmount()))));
                vos.setEventAmount(new BigDecimal(vos.getEventCount()));
            }
//            if("0".equals(overvivwVO.getOnyearFlow())||"0".equals(vo.getOnyearFlow())){
//                vos.setOnyearFlow("0");
//            }else{
//                vos.setOnyearFlow(StringUtil.coinToYuan(StringUtil.numberFormat(0,String.valueOf(overvivwVO.getOnyearFlow()),String.valueOf(vo.getOnyearFlow()))));
//            }
//            if("0".equals(overvivwVO.getComparison())||"0".equals(vo.getComparison())){
//                vos.setComparison("0");
//            }else{
//                vos.setComparison(StringUtil.coinToYuan(StringUtil.numberFormat(0,String.valueOf(overvivwVO.getComparison()),String.valueOf(vo.getComparison()))));
//            }
           overvivwVOList.add(vos);
        }
        return overvivwVOList;
    }

    private  OvervivwVO getOvervivwVO(String eventDate,List<OvervivwVO> newUserList){
        OvervivwVO vo=new OvervivwVO();
        for (OvervivwVO overvivwVO:newUserList){
            if(eventDate.equals(overvivwVO.getEventDate())){
                vo= overvivwVO;
                break;
            }
        }
        return vo;
    }

    //同比环比时间处理
    private OverviewReq getOverviewReq(OverviewReq overviewReq,String startDate,String endDate,int n){
        if (n == -1){
            overviewReq.setStartDate(DateUtil.getOneYearYYYYMMDD(startDate,n));
            overviewReq.setEndDate(DateUtil.getOneYearYYYYMMDD(endDate,n));
        }else {
            overviewReq.setStartDate(DateUtil.getOneDayYYYYMMDD(startDate,n));
            overviewReq.setEndDate(DateUtil.getOneDayYYYYMMDD(endDate,n));
        }

        return  overviewReq;
    }

    private void supplementList(List<OvervivwVO> overvivwVOList,List<String> dateList){
        overvivwVOList = overvivwVOList==null? new ArrayList<>():overvivwVOList;

        for (String st:dateList){
            if(!P(st,overvivwVOList)){
                OvervivwVO overvivwVO=new OvervivwVO();
                overvivwVO.setEventDate(st);
                overvivwVO.setEventCount("0");
                overvivwVO.setComparison("0");
                overvivwVO.setEventAmount(BigDecimal.ZERO);
                overvivwVO.setComparison("0");
                overvivwVO.setOnyearFlow("0");
                overvivwVOList.add(overvivwVO);
            }
        }
    }

    private void supplementPlatformList(List<OvervivwVO> overvivwVOList,List<String> dateList){
        overvivwVOList = overvivwVOList==null? new ArrayList<>():overvivwVOList;

        List<String> platforms=  overvivwVOList.stream().map(OvervivwVO::getPlatformType).collect(Collectors.toList())
                .stream().distinct().collect(Collectors.toList());

        for (String st:dateList){
            for (String plat : platforms){
                if(!P(st,overvivwVOList) && !checkDatePlat(st,plat,overvivwVOList)){
                    OvervivwVO overvivwVO=new OvervivwVO();
                    overvivwVO.setEventDate(st);
                    overvivwVO.setPlatformType(plat);
                    overvivwVO.setEventCount("0");
                    overvivwVO.setComparison("0");
                    overvivwVO.setEventAmount(BigDecimal.ZERO);
                    overvivwVO.setComparison("0");
                    overvivwVO.setOnyearFlow("0");
                    overvivwVOList.add(overvivwVO);
                }
            }
        }

    }

    private OvervivwResVO getOvervivwRes(OverviewReq overviewReq){
        OvervivwResVO overviewRes = new OvervivwResVO();
        String endDate = overviewReq.getEndDate();
        List<OvervivwVO> overvivwVOList=overviewService.overvivwVOList(overviewReq);

        if(!PLATFORMLIST.equals(overviewReq.getTaskType())){
            supplementList(overvivwVOList,DateUtil.getBetweenDates(overviewReq.getStartDate(),overviewReq.getEndDate()));

            BigDecimal totalAmount = overvivwVOList.stream().map(OvervivwVO::getEventAmount).reduce(BigDecimal::add).get();
            //求平均值
            BigDecimal avgAmount = totalAmount.divide(BigDecimal.valueOf(overvivwVOList.size()), 2, BigDecimal.ROUND_HALF_UP);

            overviewRes.setTotalNum(totalAmount);
            overviewRes.setAvgNum(avgAmount);

            BigDecimal showAmount = getDateAmount(endDate,overvivwVOList);
            overviewRes.setEventAmount(showAmount);
            overviewRes.setEventCount(showAmount.toString());

            //环比
            getOverviewReq(overviewReq,endDate,endDate,YEAR_ON_YEAR);
            List<OvervivwVO> overvivwVOListA=overviewService.overvivwVOList(overviewReq);
            BigDecimal onyearFlow = BigDecimal.ZERO;
            if (overvivwVOListA != null && overvivwVOListA.size() > 0){
                onyearFlow = overvivwVOListA.stream().map(OvervivwVO::getEventAmount).reduce(BigDecimal::add).get();
            }
            overviewRes.setOnyearFlow(onyearFlow.toString());

            //同比
            getOverviewReq(overviewReq,endDate,endDate,CHAIN_COMPARISON);
            List<OvervivwVO> overvivwVOListB=overviewService.overvivwVOList(overviewReq);
            BigDecimal comparison = BigDecimal.ZERO;
            if (overvivwVOListB != null && overvivwVOListB.size() > 0){
                comparison = overvivwVOListB.stream().map(OvervivwVO::getEventAmount).reduce(BigDecimal::add).get();
            }
            overviewRes.setComparison(comparison.toString());
        }else{
            supplementPlatformList(overvivwVOList,DateUtil.getBetweenDates(overviewReq.getStartDate(),overviewReq.getEndDate()));
            overviewRes.setTotalNum(BigDecimal.ZERO);
            overviewRes.setAvgNum(BigDecimal.ZERO);
            overviewRes.setEventAmount(BigDecimal.ZERO);
        }


        List<OvervivwVO> sortList = overvivwVOList.stream().sorted(Comparator.comparing(OvervivwVO::getEventDate)).collect(Collectors.toList());
        overviewRes.setOvervivwList(sortList);

        return overviewRes;
    }

    //查询事件对应的统数据列表
    public  List<OvervivwVO> overvivwVOList(OverviewReq overviewReq){

        List<OvervivwVO> overvivwVOList=overviewService.overvivwVOList(overviewReq);

        List<String> list= DateUtil.getBetweenDates(overviewReq.getStartDate(),overviewReq.getEndDate());

        for (String st:list){
            if(!P(st,overvivwVOList)){
                OvervivwVO overvivwVO=new OvervivwVO();
                overvivwVO.setEventDate(st);
                overvivwVO.setEventCount("0");
                overvivwVO.setComparison("0");
                overvivwVOList.add(overvivwVO);
            }
        }
        unitOvervivwVOList(overvivwVOList,overviewReq);
        return  overvivwVOList;
    }


    //查询同比环比
    public void unitOvervivwVOList(List<OvervivwVO> overvivwVOList,OverviewReq overviewReq){
        List<String> stringList =new ArrayList<>();
        if(!"".equals(overviewReq.getCombine())){
            stringList= DateUtil.getBetweenDates(overviewReq.getStartContrastDate(),overviewReq.getEndContrastDate());
        }
        //按照日期升序排列
        overvivwVOList.sort(comparing(OvervivwVO::getEventDate));
        //查询环比同比
        for (OvervivwVO overvivwVO:overvivwVOList){
            String comparison ="0";
            if(!"".equals(overviewReq.getCombine())){
                comparison=contrast(stringList,overviewReq);
                if(ONYEARFLOW.equals(overviewReq.getCombine())){
                    overvivwVO.setOnyearFlow(comparison);
                }else{
                    overvivwVO.setComparison(comparison);
                }
            }else{
                overvivwVO.setOnyearFlow(comparison);
                overvivwVO.setComparison(comparison);
            }
        }
    }

    public   Boolean  P(String t,List<OvervivwVO> overvivwVOList){
        Boolean p= false;
        for (OvervivwVO overvivwVO:overvivwVOList){
            if(t.equals(overvivwVO.getEventDate())){
                p= true;
                break;
            }
        }
        return p;
    }

    public   Boolean  checkDatePlat(String d,String plat,List<OvervivwVO> overvivwVOList){
        Boolean p= false;
        for (OvervivwVO overvivwVO:overvivwVOList){
            if(d.equals(overvivwVO.getEventDate()) && plat.equals(overvivwVO.getPlatformType())){
                p= true;
                break;
            }
        }
        return p;
    }

    private  String contrast(List<String> stringList,OverviewReq overviewReq){
        String n="0";
        //按照日期升序排列
        Collections.sort(stringList);
        for (String s:stringList){
            overviewReq.setStartDate(s);
            overviewReq.setEndDate(s);
            n=overviewService.overvivwVOListCount(overviewReq);
            stringList.remove(s);
            break;
        }
        return n;
    }

    public static BigDecimal getDateAmount(String eventDate,List<OvervivwVO> overviewReqList){
        Optional<OvervivwVO> optional = overviewReqList.stream().filter(property -> property.getEventDate().equals(eventDate)).findFirst();
        if (optional.isPresent()) {
            // 存在
            OvervivwVO so =  optional.get();
            return so.getEventAmount();
        } else {
            // 不存在
        }
        return BigDecimal.ZERO;
    }

   /* @ResponseBody
    @PostMapping("/findHeat")
    @ApiOperation(value = "查询热力分析", notes = "查询热力分析")
    public R findHeat(@RequestBody String  jsonString) {
        //String转json
        JSONObject obj=JSONObject.parseObject(jsonString);
        String startDate=DateUtil.dateYYYYmmdd(obj.getString("startDate"));
        String endDate=DateUtil.dateYYYYmmdd(obj.getString("endDate"));
        String ruleExpression= obj.getString("ruleExpression");
        JSONArray jsonArray =JSONArray.parseArray(ruleExpression);
        //全站流量基础模型指标
        Map<String, Object> paramMap =new HashMap<>();
        OverviewReq overviewReq=new OverviewReq();
        overviewReq.setEndDate(endDate);
        overviewReq.setStartDate(startDate);
        overviewReq.setwSql(getWsql(jsonArray));
        List<HeatVO> heatList=overviewService.heatList(overviewReq);
        paramMap.put("heatList",heatList);
        return R.data(paramMap);
    }
*/
}
